import React, { Component, Fragment } from 'react';
import { formatMessage, FormattedMessage } from 'umi/locale';
import { Form, Input, Upload, Select, Button, message } from 'antd';
import { connect } from 'dva';
import styles from './BaseView.less';
import jsonDataUtils from '@/utils/jsonDataUtils';


const FormItem = Form.Item;
const { Option } = Select;

@connect(({ user }) => ({
  currentUser: user.currentUser,
}))
@Form.create()
class BaseView extends Component {
  constructor(props) {
    super(props);
    this.state = {
      userHeadImg:''
    };
  }

  componentDidMount() {
    const { dispatch } = this.props;
    setTimeout(() => {
      let currentUser = window.localStorage.getItem("currentUser")
      if(currentUser && jsonDataUtils.isJsonString(currentUser)){
        this.setState({
          userHeadImg:JSON.parse(currentUser).picture ? JSON.parse(currentUser).picture : '1'
        })
      }
    },300)
  }

  getViewDom = ref => {
    this.view = ref;
  };

  saveMessage = () => {
    let userInfo = this.props.form.getFieldsValue();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        const { dispatch, currentUser } = this.props;
        const { userHeadImg } = this.state;
        this.reqRef = requestAnimationFrame(() => {
          dispatch({
            type: 'geographic/fetch',
            payload: { nick:userInfo.name,picture:userHeadImg == '1' ? '' : userHeadImg },
            callback: res => {

              // const userData = JSON.parse(localStorage.getItem('currentUser')) ;
              // userData.nick = userInfo.name;
              //
              // window.localStorage.setItem("currentUser",JSON.stringify(userData) )
              // location.reload()
              message.info(`${res.msg}`);
                setTimeout(()=>{
                  location.reload()
                },500)
            },
          });
        });
      }
    })
  }


  checkName=(rule, value, callback)=>{
    if(value.length>20){
      callback('昵称限制20个字符')
    }else{
      callback()
    }
  };

  beforeUpload = file => {
    let b = /\.(png|jpg|gif)$/;
    let a = file.name.toLowerCase();

    const pig = b.test(a);
    const isJPG = file.type;
    const isLt2M = file.size / 1024 / 1024 < 2;

    if (!pig) {
      if (!isLt2M) {
        message.error('请上传小于2M的图片');
      } else {
        message.error('请上传图片格式');
      }
    } else {
      if (!isLt2M) {
        message.error('请上传小于2M的图片');
      }
    }
    return isJPG && isLt2M && pig;
  };

  handleChangeImage = (info, type) => {
    if (info.file.status === 'done') {
      this.setState({
        userHeadImg: info.file.response.url,
      });
    }
  };


  render() {
    const { currentUser } = this.props;
    const {
      form: { getFieldDecorator },
    } = this.props;
    const { userHeadImg } = this.state;
    return (
      <div className={styles.backgroundp}>
        <div className={styles.baseView} ref={this.getViewDom}>
          <div className={styles.left}>
            <Form layout="vertical" onSubmit={this.handleSubmit} hideRequiredMark>
              <FormItem label={formatMessage({ id: 'app.settings.basic.email' })}>
                {getFieldDecorator('email', {
                  initialValue: currentUser.username
                })(
                  <Input disabled={true} />
                )}
              </FormItem>
              <FormItem label={formatMessage({ id: 'app.settings.basic.nickname' })}>
                {getFieldDecorator('name', {
                  initialValue: currentUser.nick,
                  rules: [
                    {
                      required: true, message: '昵称不能为空'
                    },
                    {
                      validator:this.checkName
                    }
                  ],
                })(<Input placeholder='请输入用户昵称' allowClear />)}
              </FormItem>
              {/* <FormItem label={formatMessage({ id: 'app.settings.basic.phone' })}>
                {getFieldDecorator('phone', {
                  initialValue: currentUser.phone
                })(<Input disabled={true} />)}
              </FormItem> */}
              <FormItem label="用户头像">
                {getFieldDecorator('url')(
                  <Upload
                    name="file"
                    listType="picture"
                    className="avatar-uploader"
                    showUploadList={false}
                    action="/cloud/file/upload"
                    beforeUpload={this.beforeUpload}
                    onChange={this.handleChangeImage}
                    accept=".png,.jpg"
                  >
                  {
                    userHeadImg ? (
                      <img src={userHeadImg && userHeadImg != '1' ? userHeadImg : '/robotConfigImg/user.png'} alt="file" style={{marginRight:10,width:72,height:72}} />
                    ) : ''
                  }
                    
                    <Button size={'small'}>
                      选择文件
                    </Button>
                  </Upload>
                )}
              </FormItem>
              <Button type="primary" onClick={this.saveMessage}>
                <FormattedMessage
                  id="app.settings.basic.update"
                  defaultMessage="Update Information"
                />
              </Button>
            </Form>
          </div>
        </div>
      </div>
    );
  }
}

export default connect(({ user }) => ({
  currentUser: user.currentUser,
}))(BaseView);
